<template>
  <div class="maincc">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="mainor_form small-top">
          <div class="mainor_te">
            <!-- <router-link to="/commodity/cloud/library">
              <el-button class="mainor_tea">云图库</el-button>
            </router-link> -->
            <!-- <el-tooltip
              class="item marginLeft5 mainor_tei"
              effect="dark"
              placement="bottom"
            >
              <div slot="content">
                系统会自动为所有没有上传图片的商品匹配图片库中存在的图片！
              </div>
              <svg-icon icon-class="summary_question" />
            </el-tooltip> -->
          </div>
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
            id="form"
          >
            <el-form-item label="商品名称：" prop="name">
              <el-input
                v-model.trim="form.name"
                placeholder="名称"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="分类：" prop="category_id" class="wid220">
              <el-cascader
                v-model="form.category_id"
                :options="options"
                :props="defaultProps"
                @change="getArticleList"
              ></el-cascader>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
            </MainFormBtn>
          </el-form>
        </div>

        <div class="main-controls-wrap">
          <div>
            <router-link to="/commodity/cloud/pic">
              <el-button>导入图片</el-button>
            </router-link>
            <el-button @click="exportImg" :loading="exportImgLoading">导出图片</el-button>
          </div>
        </div>

        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.list.data"
          element-loading-text="加载中"
          fit
          highlight-current-row
          :header-cell-class-name="this.$verticaline"
          :height="borderHeight - 46"
          :header-cell-style="tableHeightStyle"
        >
          <el-table-column
            label="商品名称"
            prop="name"
            :show-overflow-tooltip="true"
            width="500"
          >
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column
            label="商品图片"
            :show-overflow-tooltip="true"
            class-name="main_table"
          >
            <template slot-scope="scope">
              <div class="image_gd">
                <img
                  :src="puzzleImg"
                  v-if="scope.row.images.length == 0"
                  class="demo_eer"
                />
                <ul>
                  <draggable
                    v-model="scope.row.images"
                    class="box"
                    @end="
                      (e) => {
                        end(e, scope.$index);
                      }
                    "
                    v-bind="{
                      animation: 150,
                      sort: true,
                      forceFallback: true,
                      ghostClass: 'sortable-ghost',
                      fallbackOnBody: true,
                      disabled:
                        scope.row.images.length > 1 ? scope.row.disabled : true,
                    }"
                  >
                    <li
                      class="demo-image"
                      v-for="(item, index) in scope.row.images"
                      :key="index"
                      @mouseover="item.show = true"
                      @mouseleave="item.show = false"
                    >
                      <label
                        class="el-upload-list__item-status-label"
                        v-if="item.main == 1"
                      >
                        <i class="el-icon-upload-success el-icon-check"></i>
                      </label>
                      <el-image fit="fill" :src="item.url">
                        <div slot="error" class="image-slot">
                          <img :src="item.url" />
                        </div>
                      </el-image>
                      <div class="boxdq image_po" v-if="item.show">
                        <span title="设置主图">
                          <svg-icon
                            icon-class="commodity_graph"
                            @click.stop="images_main(item.id)"
                            @mouseover="scope.row.disabled = true"
                            @mouseleave="scope.row.disabled = false"
                          />
                        </span>
                        <span title="设置规格">
                          <svg-icon
                            icon-class="bind"
                            @click.stop="bindImages(item)"
                            @mouseover="scope.row.disabled = true"
                            @mouseleave="scope.row.disabled = false"
                          />
                        </span>
                        <span title="删除">
                          <svg-icon
                            icon-class="commodity_delete"
                            @click.prevent="
                              (id = scope.row.id),
                                delet(scope.$index, index, item.id)
                            "
                            @mouseover="scope.row.disabled = true"
                            @mouseleave="scope.row.disabled = false"
                          />
                        </span>
                      </div>
                    </li>
                  </draggable>
                </ul>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="300"
            class-name="main_hei"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click="
                  (id = scope.row.id),
                    (addedFormVisible = true),
                    edit_assig(scope.$index)
                "
                >添加</el-link
              >
              <!-- <el-link
                  type="success"
                  @click="
                    (e) => {
                      images_match(e, scope.row.id, scope.row.name);
                    }
                  "
                  v-repeatClick
                  >匹配</el-link
                > -->
            </template>
          </el-table-column>
        </el-table>
        <div class="main_num boxdq marginTop10">
          <div class="main_num_l box">
            <p>
              <em>商品图片可拖动排序！</em>
            </p>
          </div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>

        <el-dialog
          title="绑定图片"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="close"
          :visible.sync="BindImageVisible"
          class="main_dialog dialog600"
        >
          <el-form
            :inline="false"
            :model="bind"
            :rules="rules"
            class="demo-form-inline"
            ref="BindImageFrom"
            label-width="120px"
          >
            <el-form-item label="已绑定规格：">
              {{ bindSpuEd }}
            </el-form-item>
            <el-form-item label="商品规格：">
              <el-select v-model="bind.goods_spu_id" placeholder="请选择">
                <el-option
                  v-for="item in spulist"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="(BindImageVisible = false), close()"
              >取 消</el-button
            >
            <el-button type="primary" @click="send_bind">确 定</el-button>
          </div>
        </el-dialog>
        <el-dialog
          title="添加商品图片（最多可上传五张）"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="close"
          :visible.sync="addedFormVisible"
          class="main_dialog dialog600"
        >
          <el-form
            :inline="false"
            :model="info"
            :rules="rules"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="120px"
          >
            <el-form-item label="商品图片：" prop="pics">
              <div class="main_uqr">
                <div class="main_upImg">
                  <el-upload
                    :headers="{
                      Authorization: getToken(),
                    }"
                    :action="uploadPath"
                    list-type="picture-card"
                    :on-success="handSuccess"
                    :before-upload="beforeUpload"
                    :on-preview="handlePictureCardPreview"
                    :limit="5"
                    :show-file-list="false"
                    :file-list="filelist"
                  >
                    <span slot="default">
                      <svg
                        aria-hidden="true"
                        class="main_page_svg"
                        width="32"
                        height="27"
                      >
                        <use xlink:href="#icon-commodit_camera" />
                      </svg>
                    </span>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img :src="dialogImageUrl" alt />
                  </el-dialog>
                  <div class="clearfix"></div>
                </div>
                <div class="main_uqr_u">
                  <ul class="boxha">
                    <li v-for="(pics, index) in info.pics" :key="index">
                      <label
                        class="el-upload-list__item-status-label"
                        v-if="pics.main == 1"
                      >
                        <i class="el-icon-upload-success el-icon-check"></i>
                      </label>
                      <el-image
                        fit="fill"
                        style="height: 120px; width: 120px"
                        :src="pics.url"
                        :preview-src-list="album"
                      >
                        <div slot="error" class="image-slot">
                          <img :src="puzzleImg" />
                        </div>
                      </el-image>
                    </li>
                  </ul>
                </div>
              </div>
              <div class="clearfix"></div>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="(addedFormVisible = false), close()"
              >取 消</el-button
            >
            <el-button type="primary" @click="setupmine" v-repeatClick
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import { mapGetters } from "vuex";
import {
  images_index,
  images_sort,
  images_main,
  images_add,
  images_delete,
  images_match,
  images_bind,
  exportImage,
} from "@/api/commodity/commodity_Cloud";
import { goods_info, goods_base } from "@/api/commodity/commodityList";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import { recursion, category, fileDownLoad } from "@/utils/index";
import rules from "@/rules/commodity/commodity_Cloud";
import draggable from "vuedraggable";
import { uploadPath, puzzleImg } from "@/api/currency";

export default {
  mixins: [mixins],
  computed: {
    ...mapGetters(["avatar"]),
  },
  components: {
    draggable,
  },
  data() {
    return {
      // 新增
      info: {
        pics: [],
      },
      album: [],
      id: 0,
      addedFormVisible: false,
      BindImageVisible: false,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 搜索
      form: {
        name: "",
        pid: "",
        category_id: [],
      },
      // 列表数据
      list: {
        list: {
          data: [],
        },
      },
      puzzleImg,
      listLoading: false,
      // 验证
      rules,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      // 上传图片
      filelist: [],
      uploadPath,
      dialogImageUrl: "",
      dialogVisible: false,
      // 绑定图片规格
      baseInfo: "",
      spulist: [],
      issend: false,
      bindSpuEd: "",
      bind: {
        goods_spu_id: "",
        img_id: "",
      },
      exportImgLoading: false, // 订单导出loading
    };
  },
  activated() {
    this.getNumerical(190);
    // 列表
    this.goods_base();
    this.images_index();
  },
  created() {},
  methods: {
    reset() {
      this.$refs['userListFrom'].resetFields();
      this.images_index();
    },
    startGetting() {
      this.getArticleList();
    },
    goods_base() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      return new Promise((resolve, reject) => {
        goods_base(data).then((res) => {
          if (res.errcode == 0) {
            this.baseInfo = res.data;
            // 在数据更新后执行
            this.$nextTick(() => {
              // myTable是表格的ref属性值
              if (
                this.$refs.multipleTable &&
                this.$refs.multipleTable.doLayout
              ) {
                this.$refs.multipleTable.doLayout();
              }
            });
            resolve();
          } else {
            this.$message.error(res.errmsg);
          }
        });
      });
    },
    // 获取商品详情
    goods_info(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      goods_info(data).then((res) => {
        if (res.errcode == 0) {
          (this.spulist = []), (this.bind.goods_spu_id = "");
          res.data.info.spu.map((e) => {
            this.baseInfo.unit.forEach((item) => {
              if (item.id == e.unit) {
                let data = {};
                (data.id = e.id), (data.title = item.title);
                this.spulist.push(data);
                return item.title;
              }
            });
          });
          if (res.data.info.images) {
            let text = "";
            res.data.info.images.forEach((e) => {
              if (this.bind.img_id == e.id) {
                let data = this.spulist.find((item) => {
                  return item.id == e.goods_spu_id;
                });
                if (data) {
                  text = (text === "" ? text : text + ",") + data.title;
                }
              }
            });
            this.bindSpuEd = text === "" ? "未绑定任何规格" : text;
          }

          this.BindImageVisible = true;
          this.bind.goods_spu_id = this.spulist[0].id;
          this.issend = false;
        } else {
          this.$message.error(res.errmsg);
          this.issend = false;
        }
      });
    },
    send_bind() {
      if (this.issend) {
        return;
      }
      this.issend = true;
      this.$refs["BindImageFrom"].validate((valid) => {
        if (valid) {
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            this.bind
          );
          images_bind(data).then((res) => {
            if (res.errcode == 0) {
              this.$message.success("绑定成功");
              // console.log(res.data);
              this.BindImageVisible = false;
            } else {
              this.$message.error(res.errmsg);
              this.issend = false;
            }
          });
        }
      });
    },
    // 关闭清空表单
    close() {
      this.info = {
        pics: [],
      };
      this.filelist = [];
      this.album = [];
      this.$refs["userListFrom"].clearValidate();
      this.$refs["BindImageFrom"].clearValidate();
    },
    // 上传图片-成功
    handSuccess(res, file, fileList) {
      // console.log(res, file, fileList);
      if (this.info.pics.length < 5) {
        this.info.pics.push({
          main: 0,
          path: res.data.path,
          url: res.data.src,
        });
        this.album.push(res.data.src);
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 1MB!");
        return isLt2M;
      }
      if (this.info.pics.length == 5) {
        this.$message.error("上传商品图片不能超过5张!");
        return false;
      }
    },
    // 上传图片-查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 编辑赋值
    edit_assig(index) {
      let images = JSON.parse(
        JSON.stringify(this.list.list.data[index].images)
      );
      this.album = images.map((e) => e.url);
      this.info = {
        pics: images,
      };
    },
    // 确认
    setupmine() {
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          let info = JSON.parse(JSON.stringify(this.info));
          info.pics = JSON.stringify(info.pics.map((p) => p.path));
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
                  apiUrl().appsecret
              ),
            },
            apiUrl().name,
            info,
            { id: this.id }
          );
          images_add(data).then((res) => {
            this.addedFormVisible = false;
            if (res.errcode == 0) {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.images_index();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },
    bindImages(item) {
      console.log(item);
      this.bind.img_id = item.id;
      this.goods_info(item.goods_id);
    },
    // 删除
    delet(index, index1, id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      this.$confirm("是否删除商品图片?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          images_delete(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.list.list.data[index].images.splice(index1, 1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 匹配
    images_match(e, id, name) {
      if (e.path[1].disabled) {
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id, name: name })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id, name: name }
      );
      images_match(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "匹配成功",
            type: "success",
          });
          this.images_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 设置主图
    images_main(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      images_main(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "设置主图成功",
            type: "success",
          });
          this.images_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 监听拖动
    end(e, index) {
      let arry = JSON.parse(JSON.stringify(this.list.list.data[index].images));
      arry.pics = JSON.stringify(arry.map((p) => p.id));
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { pics: arry.pics }
      );
      images_sort(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "排序成功",
            type: "success",
          });
          this.images_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.images_index();
    },
    changePage(page) {
      this.current.page = page;
      this.images_index();
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.images_index();
    },
    // 列表
    images_index() {
      this.listLoading = true;
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, form, this.current)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form,
        this.current
      );
      images_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.options = recursion(res.data.categoryList, true);
          res.data.list.data.forEach((e) => {
            e.images.forEach((a) => {
              e.disabled = false;
              a.show = false;
              a.url = this.avatar.domain + "/" + a.path;
            });
          });
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 导出图片
    exportImg() {
      this.exportImgLoading = true;
      exportImage(packApi()).then(res=> {
        fileDownLoad(res, "商品图片");
        this.exportImgLoading = false;
        this.$message.success("导出成功")
      }).catch(() => {
        this.exportImgLoading = false;
        this.$message.error("导出失败");
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.maincc {
  .mainor_form form {
    width: calc(100% - 200px);
  }
  .main_table {
    .image_gd {
      height: 100px;
    }
    .demo-image {
      position: relative;
      border: 1px solid #f8f8f9;
      overflow: hidden;
      display: flex;
      flex-direction: row;
      .el-upload-list__item-status-label {
        position: absolute;
        right: -15px;
        top: -6px;
        z-index: 91;
        width: 40px;
        height: 24px;
        background: #13ce66;
        text-align: center;
        -webkit-transform: rotate(45deg);
        transform: rotate(45deg);
        -webkit-box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
        box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
        display: block;
        i {
          font-size: 12px;
          margin-top: 11px;
          color: $white;
          -webkit-transform: rotate(-45deg);
          transform: rotate(-45deg);
        }
      }
      .image_po {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 92;
        width: 100%;
        height: 100%;
        padding-left: 15px;
        border-radius: 4px;
        padding-right: 15px;
        background: $subMenuHover;
        span {
          &:first-child {
            .svg-icon {
              font-size: $font_18;
            }
          }
        }
        .svg-icon {
          font-size: $font_16;
          color: $white;
          &:hover {
            cursor: pointer;
          }
        }
      }

      &:first-child {
        margin-left: 0;
      }
      /deep/.el-image__inner {
        width: 100px;
        height: 100px;
      }
      img {
        width: 100px;
        height: 100px;
      }
    }
  }
  .maincc_list {
    ul {
      margin-left: -15px;
      li {
        margin-bottom: 15px;
        width: 11.1%;
        .maincc_list_b {
          margin-left: 15px;
          height: 200px;
          background: $white;
          box-shadow: 0px 0px 8px 1px #413f3f14;
          border-radius: 2px;
          position: relative;
        }
        p {
          position: absolute;
          bottom: 0;
          height: 35px;
          line-height: 35px;
          background: $menuActiveText;
          font-size: $font_14;
          color: $white;
          padding-left: 10px;
          padding-right: 10px;
          overflow: hidden;
          width: 100%;
        }
        &:hover {
          cursor: pointer;
        }
      }
    }
  }
  .demo_eer {
    width: 100px;
    height: 100px;
    border: 1px solid #f8f8f9;
  }
  .boxha {
    li {
      &:nth-child(n+3) {
        margin-top: 20px;
      }
    }
  }

  @media screen and (max-width: 1600px) {
    .maincc_list ul li {
      width: 14.28%;
    }
  }
  @media screen and (max-width: 1300px) {
    .maincc_list ul li {
      width: 20%;
    }
  }
  @media screen and (max-width: 800px) {
    .maincc_list ul li {
      width: 33.33%;
    }
  }
}
/deep/ .el-form-item--small.el-form-item {
  margin-bottom: 10px !important;
}
/deep/.el-image {
  width: 100px;
  height: 100px;
}
/deep/.el-table__body tr.current-row > td.el-table__cell,
.el-table__body tr.selection-row > td.el-table__cell {
  background: none;
}
/deep/.el-table__body tr:hover > td {
  background: rgba($color: #03a98e, $alpha: 0.07) !important;
}
</style>
